//
//  Pool.m
//  sfdcFuse
//
//  Created by Simon Fell on 2/20/07.
//  Copyright 2007 Simon Fell. All rights reserved.
//

#import "Pool.h"


@implementation Pool

- (id)initWithMaster:(id)masterObject maxPoolItems:(int)max {
	self = [super init];
	spares = [[NSMutableArray arrayWithCapacity:max] retain];
	maxToKeep = max;
	master = [masterObject retain];
	return self;
}

- (void)dealloc {
	[master release];
	[spares release];
	[super dealloc];
}

- (id)checkout {
	id spare = nil;
	@synchronized (spares) {
		if ([spares count] > 0) {
			spare = [spares lastObject];
			[spares removeLastObject];
		}
	}
	if (spare == nil) {
		@synchronized (master) {
			spare = [master copyWithZone:nil];
		}
	}
	return spare;
}

- (void)checkin:(id)item {
	@synchronized (spares) {
		if ([spares count] < maxToKeep)
			[spares addObject:item];
	}
}

@end
